﻿/**********************************************************************************
 * Project Name :   
 * Remarks      :  
 * Class Name   :  XmlExtensionMethods 
 * Version      :  v1.0.0.0 
 * Author       :  Joey Liang 
 * Description  : 
 * Created Time :  2013/10/20 20:44:20
 * Update Man   :  Joey Liang
 * Update Time  :  2013/10/20 20:44:20
************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace IdleTest.DemoBeTest
{
    public static class XmlExtensionMethods
    {
        /// <summary>
        /// 获取XML节点的属性值
        /// </summary>
        /// <param name="node">节点</param>
        /// <param name="attr">属性名</param>
        public static string GetAttribute(this XmlNode node, string attr)
        {
            if (string.IsNullOrEmpty(attr) || node.Attributes[attr] == null)
            {
                return string.Empty;
            }

            return node.Attributes[attr].Value;
        }

        /// <summary>
        /// 获取XML节点的属性值
        /// </summary>
        /// <param name="node">节点</param>
        /// <param name="attr">属性名</param>
        public static T GetAttribute<T>(this XmlNode node, string attr)
        {
            if (string.IsNullOrEmpty(attr) || node.Attributes[attr] == null
                || string.IsNullOrEmpty(node.Attributes[attr].Value))
            {
                return default(T);
            }

            return (T)Convert.ChangeType(node.Attributes[attr].Value, typeof(T));
        }

        /// <summary>
        /// 查找满足条件的节点
        /// </summary>
        public static XmlNode Find(this XmlNodeList source, Func<XmlNode, bool> func)
        {
            foreach (object o in source)
            {
                XmlNode item = o as XmlNode;
                if (item != null && func(item))
                    return item;
            }

            return null;
        }

        /// <summary>
        /// 查找满足条件的节点集合
        /// </summary>
        public static ICollection<XmlNode> FindAll(this XmlNodeList source, Func<XmlNode, bool> func)
        {
            List<XmlNode> list = new List<XmlNode>();
            foreach (XmlNode item in source)
            {
                if (func(item))
                    list.Add(item);
            }

            return list;
        }
    }
}
